import {
  Button, message, Spin
} from 'antd';
import { ProgressBar, CheckList } from 'antd-mobile';
import { useSelector, useDispatch } from 'react-redux';
import { useParams, useHistory } from 'react-router-dom';
import { useBoolean, useRequest } from 'ahooks';

import { useEffect, useCallback } from 'react';
import { useCheckQuestionRange, useCheckMissedQuestion } from './hooks';
import * as API from '../../../../constants/api-constants';
import { TOTAL_QUESTION } from '../../../../constants/app-constants';
import { updateScoreAction } from '../../actions';

import style from './style.module.less';

const { title } = style;
const { Item } = CheckList;

interface FooterProps {
  questionnaireUuid: string,
  currentQuestionIndex: number,
  isInSelectProgress: boolean,
  currentQuestionScore: number | undefined
}

const Footer = ({
  questionnaireUuid,
  currentQuestionIndex,
  isInSelectProgress,
  currentQuestionScore
}: FooterProps) => {
  const [preDisable, {
    setTrue: setPreDisableTrue,
    setFalse: setPreDisableFalse
  }] = useBoolean(false);
  const history = useHistory();
  /** 进度百分比 */
  const processPercent = ((currentQuestionIndex + 1) / TOTAL_QUESTION) * 100;
  /** 是否填写最后一项用户信息 */
  const isAnswerLastQuestion = !currentQuestionScore;
  const isInProgress = isAnswerLastQuestion || isInSelectProgress;

  // 设置按钮展示状态
  useEffect(() => {
    // 设置“上一项”按钮状态
    if (currentQuestionIndex === 0) {
      setPreDisableTrue();
    }
    if (currentQuestionIndex !== 0) {
      setPreDisableFalse();
    }
  }, [currentQuestionIndex]);

  const getNextButtonColorStyleObj = useCallback(
    (_isInProgress) => (
      _isInProgress
        ? { color: '#ddd' }
        : undefined
    ),
    []
  );

  const getPreButtonColorStyleObj = useCallback(
    (_preDisable) => (
      _preDisable
        ? { color: '#ddd' }
        : undefined
    ),
    []
  );

  return (
    <div className={style.footer}>
      <ProgressBar
        percent={processPercent}
        style={{
          '--track-width': '5px',
        }}
      />
      <div className={style['basic-footer']}>
        <Button
          style={getPreButtonColorStyleObj(preDisable)}
          type="link"
          disabled={preDisable}
          onClick={() => {
            history.push(`/questionAnswer/home/${questionnaireUuid}/question/${currentQuestionIndex - 1}`);
          }}
        >
          上一项
        </Button>
        <span className={style.process}>
          {currentQuestionIndex + 1}
          /
          {TOTAL_QUESTION}
        </span>
        <Button
          style={getNextButtonColorStyleObj(isInProgress)}
          disabled={isInProgress}
          type="link"
          onClick={() => {
            history.push(`/questionAnswer/home/${questionnaireUuid}/question/${currentQuestionIndex + 1}`);
          }}
        >
          下一项
        </Button>
      </div>
    </div>
  );
};

const Question = () => {
  const history = useHistory();
  const dispatch = useDispatch();

  const { index, questionnaireUuid } = useParams<{
    index: string,
    questionnaireUuid: string
  }>();

  // 当前questionIndex
  const currentQuestionIndex = Number(index);
  const {
    currentQuestion,
    userUuid,
    currentQuestionScore
  } = useSelector((
    storeState: QA.ReduxState
  ) => ({
    currentQuestion: storeState.questionList[currentQuestionIndex],
    userUuid: storeState.userUuid,
    currentQuestionScore: storeState.scoreList[currentQuestionIndex]
  }));

  // 用户是否跳题
  useCheckMissedQuestion(
    questionnaireUuid,
    currentQuestionIndex,
  );

  // 判断路由范围
  useCheckQuestionRange(
    currentQuestionIndex,
    questionnaireUuid
  );

  /**
   * 保存问题答案
   */
  const { run, loading: isInSelectProgress } = useRequest((score) => ({
    url: API.ANSWER,
    method: 'POST',
    data: {
      questionnaireUuid,
      userUuid,
      questionUuid: currentQuestion?.uuid,
      score,
    }
  }), {
    manual: true,
    onSuccess: () => {
      // 如果已经回答完问卷，则跳转回答成功页
      if (currentQuestionIndex + 1 === TOTAL_QUESTION) {
        history.push(`/questionAnswer/home/${questionnaireUuid}/successResult`);
        return;
      }
      history.push(`/questionAnswer/home/${questionnaireUuid}/question/${currentQuestionIndex + 1}`);
    },
    onError: () => {
      dispatch(updateScoreAction({
        index: currentQuestionIndex,
        score: undefined
      }));
      message.error('答案保存失败！请重试！');
    },
  });

  const handleRadioClick = (score?: number) => {
    if (!score) return;
    dispatch(updateScoreAction({
      index: currentQuestionIndex,
      score
    }));
    run(score);
  };

  const curValue = currentQuestionScore !== undefined ? [`${currentQuestionScore}`] : [];

  return (
    <div>
      <div className={style['questionnaire-information']}>
        <h1>自我评定</h1>
        <p>
          该问卷旨在帮助您了解自己近一个月的职业心理状况，
          唤醒您主动关注自身心理状况的意识，
          促进您在未来的生活和工作中遇到困难和压力时，主动进行调整，更积极地应对，实现个人成长。
        </p>
      </div>
      <div className={style['basic-question']}>
        <div className={title}>
          {`${currentQuestionIndex + 1}: ${currentQuestion.name}`}
        </div>

        <Spin spinning={isInSelectProgress}>
          <CheckList
            value={curValue}
            onChange={(
              checked: string[]
            ) => { handleRadioClick(Number(checked[0])); }}
          >
            <Item value="1">无</Item>
            <Item value="2">偶尔</Item>
            <Item value="3">有时</Item>
            <Item value="4">经常</Item>
            <Item value="5">总是</Item>
          </CheckList>
        </Spin>
      </div>
      <Footer
        questionnaireUuid={questionnaireUuid}
        currentQuestionIndex={currentQuestionIndex}
        isInSelectProgress={isInSelectProgress}
        currentQuestionScore={currentQuestionScore}
      />
    </div>
  );
};

export default Question;
